package com.fire8.dolphin.ui.plan;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.fire8.dolphin.db.PlanDAO;
import com.fire8.dolphin.model.Plan;
import com.fire8.dolphin.service.AlarmForSmsService;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.ui.contacts.ContactsActivity;
import com.fire8.dolphin.ui.wiget.CalendarGridView;
import com.fire8.dolphin.ui.wiget.CalendarGridViewAdapter;
import com.fire8.dolphin.utils.DateUtil;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;




public class PlanAddActivity2 extends Activity implements OnTouchListener
{
    
    //判断手势用
    private static final int SWIPE_MIN_DISTANCE = 120;
    
    private static final int SWIPE_MAX_OFF_PATH = 250;
    
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
    boolean isExist = false;
    
    //动画
    private Animation slideLeftIn;
    
    private Animation slideLeftOut;
    
    private Animation slideRightIn;
    
    private Animation slideRightOut;
    
    private ViewFlipper viewFlipper;
    
    GestureDetector mGesture = null;
    
    ArrayList<Date> dlist = new ArrayList<Date>();
    
    String[] hours = new String[]{"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
    String[] minutes = new String[]{"00","05","10","15","20","25","30","35","40","45","50","55"};
    
 // 基本变量
    private Context mContext = PlanAddActivity2.this;
    
    private GridView title_gView;
    
    private GridView gView1;// 上一个月
    
    private GridView gView2;// 当前月
    
    private GridView gView3;// 下一个月
    
    // private GridView gView1;
    boolean bIsSelection = false;// 是否是选择事件发生
    
    private Calendar calStartDate = Calendar.getInstance();// 当前显示的日历
    
    private Calendar calSelected = Calendar.getInstance(); // 选择的日历
    
    private Calendar calToday = Calendar.getInstance(); // 今日
    
    private CalendarGridViewAdapter gAdapter;
    
    private CalendarGridViewAdapter gAdapter1;
    
    private CalendarGridViewAdapter gAdapter3;
    
    private EditText txtTitle;//计划内容
    // 顶部按钮
    private Button btnToday = null;
    
    //private RelativeLayout mainLayout;
    private LinearLayout mainLayout;
    
    //确定按钮
    private Button btnEnter = null;
    //邀请的好友
    private TextView tvFriends;
    //显示分钟数和小时数
    TextView tvHour;
    TextView tvMinute;
    
    //时间选择按钮
    ImageView btnHourUp;
    ImageView btnHourDown;
    ImageView btnMinuteUp;
    ImageView btnMinuteDown;
    CheckBox checkbox;
    private ArrayList<Plan> planList2 = new ArrayList<Plan>();//需要插入数据库的
    private DolphinApplication app;
    private AlarmManager aManager;//闹钟管理器
    private PlanDAO pdDAO;
    private ProgressDialog progressDialog = null;//提示滚动条
    /**邀请的好友的电话号码**/
    private ArrayList<String> phoneList = new ArrayList<String>();//邀请的好友的电话号码
    //
    private int iMonthViewCurrentMonth = 0; // 当前视图月
    
    private int iMonthViewCurrentYear = 0; // 当前视图年
    
    private int iFirstDayOfWeek = Calendar.MONDAY;
    
    private static final int mainLayoutID = 88; // 设置主布局ID
    
    private static final int titleLayoutID = 77; // title布局ID
    
    private static final int caltitleLayoutID = 66; // title布局ID
    
    private static final int calLayoutID = 55; // 日历布局ID
    
    private static final int calButtomLineId = PlanAddActivity2.class.hashCode();//日历底部的线条ID

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        app = (DolphinApplication)getApplication();
        pdDAO = new PlanDAO(this);
        aManager = (AlarmManager)getSystemService(Service.ALARM_SERVICE);
        setContentView(generateContentView());
        setTitle("选择日期");
        setTitleColor(getResources().getColor(R.color.balck));
        
        UpdateStartDateForMonth();
        
        slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this,
                R.anim.slide_right_out);
        
        slideLeftIn.setAnimationListener(animationListener);
        slideLeftOut.setAnimationListener(animationListener);
        slideRightIn.setAnimationListener(animationListener);
        slideRightOut.setAnimationListener(animationListener);
        mGesture = new GestureDetector(this, new GestureListener());
        //保存按钮事件
        btnEnter.setOnClickListener(new SavePlanListener());
        
        List<Date> tempList = (ArrayList<Date>)getIntent().getSerializableExtra("alarmDateList");
        if(tempList!=null && !tempList.isEmpty()){
            dlist.addAll(tempList);
            setAdpterSelectList(dlist);
        }
        btnHourUp.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Integer index = (Integer)tvHour.getTag();
                if(index>=23)
                {
                    index=0;
                }else
                {
                    index++;
                }
                tvHour.setTag(index);
                tvHour.setText(hours[index]);
            }
        });
        btnHourDown.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Integer index = (Integer)tvHour.getTag();
                if(index<=0)
                {
                    index=23;
                }else
                {
                    index--;
                }
                tvHour.setTag(index);
                tvHour.setText(hours[index]);
            }
        });
        btnMinuteUp.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Integer index = (Integer)tvMinute.getTag();
                if(index >=11)
                {
                    index = 0;
                }else
                {
                    index++;
                }
                tvMinute.setTag(index);
                tvMinute.setText(minutes[index]);
            }
        });
        btnMinuteDown.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Integer index = (Integer)tvMinute.getTag();
                if(index <=0)
                {
                    index = 11;
                }else
                {
                    index--;
                }
                tvMinute.setTag(index);
                tvMinute.setText(minutes[index]);
            }
        });
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        return mGesture.onTouchEvent(event);
    }
    
    AnimationListener animationListener = new AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {
        }
        
        @Override
        public void onAnimationRepeat(Animation animation)
        {
        }
        
        @Override
        public void onAnimationEnd(Animation animation)
        {
            //当动画完成后调用
            CreateGirdView();
        }
    };
    
    class GestureListener extends SimpleOnGestureListener
    {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY)
        {
            try
            {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
                {
                    viewFlipper.setInAnimation(slideLeftIn);
                    viewFlipper.setOutAnimation(slideLeftOut);
                    viewFlipper.showNext();
                    setNextViewItem();
                    //CreateGirdView();
                    return true;
                    
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                        && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
                {
                    viewFlipper.setInAnimation(slideRightIn);
                    viewFlipper.setOutAnimation(slideRightOut);
                    viewFlipper.showPrevious();
                    setPrevViewItem();
                    //CreateGirdView();
                    return true;
                    
                }
            }
            catch (Exception e)
            {
                // nothing
            }
            return false;
        }
        
        @Override
        public boolean onSingleTapUp(MotionEvent e)
        {
            // ListView lv = getListView();
            //得到当前选中的是第几个单元格
            int pos = gView2.pointToPosition((int)e.getX(), (int)e.getY());
            LinearLayout txtDay = (LinearLayout)gView2.findViewById(pos + 5000);
            if (txtDay != null)
            {
                if (txtDay.getTag() != null)
                {
                    Date date = (Date)txtDay.getTag();
                    Log.d("date", date + "");
                    if (dlist.size() > 0)
                    {
                        for (Date temp : dlist)
                        {
                            if (temp.compareTo(date) == 0)
                            {
                                dlist.remove(temp);
                                isExist = true;
                                break;
                            }
                        }
                    }
                    else
                        isExist = false;
                    if (!isExist)
                    {
                        dlist.add(date);
                        isExist = false;
                    }
                    setAdpterSelectList(dlist);
                    Log.d("ssssszie", dlist.size() + "");

                }
            }
            
            Log.i("TEST", "onSingleTapUp -  pos=" + pos);
            
            return false;
        }
    }
    
    // / }}}
    
    
    
    
    AlertDialog.OnKeyListener onKeyListener = new AlertDialog.OnKeyListener()
    {
        
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
        {
            if (keyCode == KeyEvent.KEYCODE_BACK)
            {
                PlanAddActivity2.this.finish();
            }
            return false;
            
        }
        
    };
    
    // 生成内容视图
    private View generateContentView()
    {
        // 创建一个垂直的线性布局（整体内容）
        viewFlipper = new ViewFlipper(this);
        viewFlipper.setId(calLayoutID);
        ScrollView scrollView = new ScrollView(this);
        LayoutParams params_scrollView = new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        scrollView.setLayoutParams(params_scrollView);
        scrollView.setHorizontalScrollBarEnabled(false);
        //mainLayout = new RelativeLayout(this); // 创建一个垂直的线性布局（整体内容）
        mainLayout = new LinearLayout(this); // 创建一个垂直的线性布局（整体内容）
        mainLayout.setBackgroundColor(Color.WHITE);
        LinearLayout.LayoutParams params_main = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
        mainLayout.setLayoutParams(params_main);
        mainLayout.setId(mainLayoutID);
        //mainLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        //顶部，放个文本框，用于输入计划内容
        txtTitle = new EditText(this);
        txtTitle.setId(txtTitle.hashCode());
        txtTitle.setHint("请输入计划内容");
        LinearLayout.LayoutParams params_txt = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        params_txt.setMargins(2, 2, 2, 0);
        mainLayout.addView(txtTitle,params_txt);
        
        LinearLayout layTopControls = createLayout(LinearLayout.HORIZONTAL); // 生成顶部按钮布局
        
        generateTopButtons(layTopControls); // 生成顶部按钮 （上一月，下一月，当前月）
        LinearLayout.LayoutParams params_title = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        //params_title.topMargin = 1;
        //params_title.addRule(RelativeLayout.BELOW, txtTitle.getId());
        layTopControls.setId(titleLayoutID);
        mainLayout.addView(layTopControls, params_title);
        
        calStartDate = getCalendarStartDate();
        //日历头部，周日到周六
        setTitleGirdView();
        LinearLayout.LayoutParams params_cal_title = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        //params_cal_title.addRule(RelativeLayout.BELOW, titleLayoutID);
        params_cal_title.setMargins(2, 0, 2, 0);
        mainLayout.addView(title_gView, params_cal_title);
        
        CreateGirdView();
        
        LinearLayout.LayoutParams params_cal = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        //params_cal.addRule(RelativeLayout.BELOW, caltitleLayoutID);
        params_cal.setMargins(2, 0, 2, 0);
        viewFlipper.setLayoutParams(params_cal);
        mainLayout.addView(viewFlipper);
        
        View br = new View(this);
        //br.setId(calButtomLineId);
        LinearLayout.LayoutParams params_br = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, 1);
        br.setLayoutParams(params_br);
//        //params_br.addRule(RelativeLayout.BELOW, calLayoutID);
        params_br.setMargins(2, 0, 2, 0);
        br.setBackgroundColor(getResources().getColor(R.color.calendar_background));
        //mainLayout.addView(br, params_br);
        mainLayout.addView(br);
        LogUtil.d("添加日历底部线条");
        //绘制时间选择
        RelativeLayout timeLayout = new RelativeLayout(this);//创建时间布局
        drawTimeLayout(timeLayout);
        //华丽的分隔线
        LinearLayout line1 = new LinearLayout(this);
        line1.setId(line1.hashCode());
        LinearLayout.LayoutParams params_line1 = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, 1);
        //params_line1.addRule(RelativeLayout.BELOW, timeLayout.hashCode());
        params_line1.setMargins(4, 0, 4, 0);
        line1.setBackgroundColor(getResources().getColor(R.color.calendar_background));
        mainLayout.addView(line1, params_line1);
        //邀请好友监督
        RelativeLayout inviteLayout = drawInviteLayout(line1);
        //华丽的分隔线
        LinearLayout line2 = new LinearLayout(this);
        line2.setId(line2.hashCode());
        LinearLayout.LayoutParams params_line2 = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, 1);
        //params_line2.addRule(RelativeLayout.BELOW, inviteLayout.hashCode());
        params_line2.setMargins(4, 0, 4, 0);
        line2.setBackgroundColor(Color.GRAY);
        mainLayout.addView(line2, params_line2);
        
        
        //是否提醒复选框
        checkbox = new CheckBox(this);
        checkbox.setId(checkbox.hashCode());
        checkbox.setText("本地提醒");
        checkbox.setTextColor(Color.GRAY);
        checkbox.setChecked(true);
        LinearLayout.LayoutParams params_checkbox = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        //params_checkbox.addRule(RelativeLayout.BELOW, line2.hashCode());
        mainLayout.addView(checkbox,params_checkbox);
        
        
        
        //创建确定按钮
        btnEnter = new Button(this);
        btnEnter.setText("确定");
        btnEnter.setTextColor(getResources().getColor(R.color.white));
        btnEnter.setTextSize(23);
        btnEnter.setBackgroundResource(R.drawable.main_tab_bg);
        LinearLayout.LayoutParams params_btn = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, 90);
        //params_btn.addRule(RelativeLayout.BELOW, checkbox.hashCode());
        params_btn.setMargins(0, 10, 0, 0);
        mainLayout.addView(btnEnter,params_btn);
        
        scrollView.addView(mainLayout);
//        scrollView.setOnTouchListener(new OnTouchListener()
//        {
//            @Override
//            public boolean onTouch(View v, MotionEvent event)
//            {
//                return mGesture.onTouchEvent(event);
//            }
//        });
        return scrollView;
//        return mainLayout;
        
    }

    /**
     * 绘制邀请布局
     * <功能详细描述>
     * @param line1
     * @return [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private RelativeLayout drawInviteLayout(LinearLayout line1)
    {
        RelativeLayout inviteLayout = new RelativeLayout(this);//创建邀请布局
        inviteLayout.setId(inviteLayout.hashCode());
        
        TextView tvInviteTitle = new TextView(this);//
        tvInviteTitle.setId(tvInviteTitle.hashCode());
        tvInviteTitle.setTextColor(Color.GRAY);
        tvInviteTitle.setTextSize(24);
        tvInviteTitle.setText("邀请好友监督");
        tvInviteTitle.setPadding(5, 5, 5, 2);
        inviteLayout.addView(tvInviteTitle);
        
        tvFriends = new TextView(this);//
        tvFriends.setId(tvFriends.hashCode());
        tvFriends.setTextColor(Color.GRAY);
        tvFriends.setTextSize(14);
        tvFriends.setText("通知好友提醒您按时完成计划");
        RelativeLayout.LayoutParams params_tvFriends = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_tvFriends.addRule(RelativeLayout.BELOW, tvInviteTitle.getId());
        params_tvFriends.addRule(RelativeLayout.ALIGN_LEFT, tvInviteTitle.getId());
        params_tvFriends.leftMargin=15;
        inviteLayout.addView(tvFriends,params_tvFriends);
        
        ImageView imgOpera = new ImageView(this);
        imgOpera.setImageResource(R.drawable.sc_openablum);
        RelativeLayout.LayoutParams params_imgOpera = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_imgOpera.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params_imgOpera.addRule(RelativeLayout.CENTER_VERTICAL);
        //params_imgOpera.addRule(RelativeLayout.RIGHT_OF, tvFriends.getId());
        params_imgOpera.rightMargin=10;
        inviteLayout.addView(imgOpera,params_imgOpera);
        
        LinearLayout.LayoutParams params_invite = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        //params_invite.addRule(RelativeLayout.BELOW,line1.getId());
        mainLayout.addView(inviteLayout, params_invite);
        inviteLayout.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                //点击弹出联系人窗口
                Intent intent = new Intent(PlanAddActivity2.this,
                        ContactsActivity.class);
                startActivityForResult(intent,
                        ContactsActivity.class.hashCode());
            }
        });
        return inviteLayout;
    }

    /**
     * 绘制时间布局
     * <功能详细描述>
     * @return [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    private RelativeLayout drawTimeLayout(RelativeLayout timeLayout)
    {
        tvHour = new TextView(this);
        tvMinute = new TextView(this);
        
        //时间选择按钮
        btnHourUp = new ImageView(this);
        btnHourDown = new ImageView(this);
        btnMinuteUp = new ImageView(this);
        btnMinuteDown = new ImageView(this);
        timeLayout.setId(timeLayout.hashCode());
        
        tvHour.setId(tvHour.hashCode());
        tvHour.setTextSize(60);
        int index = (new Date()).getHours();
        tvHour.setText(hours[index]);
        tvHour.setTag(index);
        timeLayout.addView(tvHour, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        //小时的向上按钮
        
        btnHourUp.setId(btnHourUp.hashCode());
        btnHourUp.setImageDrawable(getResources().getDrawable(R.drawable.spinner_up));
        
        RelativeLayout.LayoutParams params_btnHourUp = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_btnHourUp.addRule(RelativeLayout.RIGHT_OF, tvHour.hashCode());
        params_btnHourUp.setMargins(10, 0, 10, 0);
        timeLayout.addView(btnHourUp,params_btnHourUp);
        //小时的向下按钮
        
        btnHourDown.setId(btnHourDown.hashCode());
        btnHourDown.setImageDrawable(getResources().getDrawable(R.drawable.spinner_down));
        RelativeLayout.LayoutParams params_btnHourDown = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_btnHourDown.addRule(RelativeLayout.ALIGN_LEFT, btnHourUp.hashCode());
        params_btnHourDown.addRule(RelativeLayout.BELOW, btnHourUp.hashCode());
        
        timeLayout.addView(btnHourDown,params_btnHourDown);
        
        //分钟
        
        tvMinute.setId(tvMinute.hashCode());
        tvMinute.setTextSize(60);
        tvMinute.setText("00");
        tvMinute.setTag(0);
        RelativeLayout.LayoutParams params_tvMinute = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_tvMinute.addRule(RelativeLayout.RIGHT_OF, btnHourUp.hashCode());
        
        timeLayout.addView(tvMinute, params_tvMinute);
        //分钟的向上按钮
        
        btnMinuteUp.setId(btnMinuteUp.hashCode());
        btnMinuteUp.setImageDrawable(getResources().getDrawable(R.drawable.spinner_up));
        RelativeLayout.LayoutParams params_btnMinuteUp = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_btnMinuteUp.addRule(RelativeLayout.RIGHT_OF, tvMinute.hashCode());
        
        timeLayout.addView(btnMinuteUp,params_btnMinuteUp);
        //分钟的向下按钮
        
        btnMinuteDown.setId(btnMinuteDown.hashCode());
        btnMinuteDown.setImageDrawable(getResources().getDrawable(R.drawable.spinner_down));
        RelativeLayout.LayoutParams params_btnMinuteDown = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params_btnMinuteDown.addRule(RelativeLayout.ALIGN_LEFT, btnMinuteUp.hashCode());
        params_btnMinuteDown.addRule(RelativeLayout.BELOW, btnMinuteUp.hashCode());
        
        timeLayout.addView(btnMinuteDown,params_btnMinuteDown);
        
        
        LinearLayout.LayoutParams params_timeLayout = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//        params_timeLayout.addRule(RelativeLayout.BELOW, calButtomLineId);
//        params_timeLayout.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params_timeLayout.topMargin=10;
        mainLayout.addView(timeLayout,params_timeLayout);
        return timeLayout;
    }
    
    // 创建一个线性布局
    // 参数：方向
    private LinearLayout createLayout(int iOrientation)
    {
        LinearLayout lay = new LinearLayout(this);
        LayoutParams params = new LayoutParams(
                android.view.ViewGroup.LayoutParams.FILL_PARENT,// *fill_parent，填满父控件的空白
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        params.topMargin = 10;
        // 设置布局参数
        lay.setLayoutParams(params);// *wrap_content，表示大小刚好足够显示当前控件里的内容
        lay.setOrientation(iOrientation);// 设置方向
        lay.setGravity(Gravity.LEFT);
        return lay;
    }
    
    // 生成顶部按钮
    // 参数：布局
    private void generateTopButtons(LinearLayout layTopControls)
    {
        // 创建一个当前月按钮（中间的按钮）
        btnToday = new Button(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 0, 0);
        btnToday.setPadding(0, 0, 0, 0);
        btnToday.setLayoutParams(lp);
        btnToday.setTextSize(20);
        btnToday.setBackgroundResource(Color.TRANSPARENT);//
        //btnToday.setBackgroundColor(Color.GRAY);
        // btn_cal.setBackgroundResource(R.drawable.editbox_background_normal);//
        // 设置当前月按钮的背景颜色为按钮默认颜色
        
        // 当前月的点击事件的监听
        btnToday.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View arg0)
            {
                setToDayViewItem();
            }
        });
        
        layTopControls.setGravity(Gravity.CENTER_HORIZONTAL);
        layTopControls.addView(btnToday);
        
    }
    
    private void setTitleGirdView()
    {
        
        title_gView = setGirdView();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        // params.topMargin = 5;
        title_gView.setLayoutParams(params);
        title_gView.setVerticalSpacing(0);// 垂直间隔
        title_gView.setHorizontalSpacing(0);// 水平间隔
        TitleGridAdapter titleAdapter = new TitleGridAdapter(this);
        title_gView.setAdapter(titleAdapter);// 设置菜单Adapter
        title_gView.setId(caltitleLayoutID);
    }
    
    private void CreateGirdView()
    {
        
        Calendar tempSelected1 = Calendar.getInstance(); // 临时
        Calendar tempSelected2 = Calendar.getInstance(); // 临时
        Calendar tempSelected3 = Calendar.getInstance(); // 临时
        tempSelected1.setTime(calStartDate.getTime());
        tempSelected2.setTime(calStartDate.getTime());
        tempSelected3.setTime(calStartDate.getTime());
        
        gView1 = new CalendarGridView(mContext);
        tempSelected1.add(Calendar.MONTH, -1);
        gAdapter1 = new CalendarGridViewAdapter(this, tempSelected1);
        gView1.setAdapter(gAdapter1);// 设置菜单Adapter
        gView1.setId(calLayoutID);
        
        gView2 = new CalendarGridView(mContext);
        gAdapter = new CalendarGridViewAdapter(this, tempSelected2);
        gView2.setAdapter(gAdapter);// 设置菜单Adapter
        gView2.setId(calLayoutID);
        
        gView3 = new CalendarGridView(mContext);
        tempSelected3.add(Calendar.MONTH, 1);
        gAdapter3 = new CalendarGridViewAdapter(this, tempSelected3);
        gView3.setAdapter(gAdapter3);// 设置菜单Adapter
        gView3.setId(calLayoutID);
        
        gView2.setOnTouchListener(this);
        gView1.setOnTouchListener(this);
        gView3.setOnTouchListener(this);
        
        if (viewFlipper.getChildCount() != 0)
        {
            viewFlipper.removeAllViews();
        }
        
        viewFlipper.addView(gView2);
        viewFlipper.addView(gView3);
        viewFlipper.addView(gView1);
        
        String s = calStartDate.get(Calendar.YEAR) + "-"
                + LeftPad_Tow_Zero(calStartDate.get(Calendar.MONTH) + 1);
        
        btnToday.setText(s);
    }
    
    private GridView setGirdView()
    {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        GridView gridView = new GridView(this);
        gridView.setLayoutParams(params);
        gridView.setNumColumns(7);// 设置每行列数
        gridView.setGravity(Gravity.CENTER_VERTICAL);// 位置居中
        gridView.setVerticalSpacing(1);// 垂直间隔
        gridView.setHorizontalSpacing(1);// 水平间隔
        gridView.setBackgroundColor(getResources().getColor(R.color.calendar_background));
        
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int i = display.getWidth() / 7;
        int j = display.getWidth() - (i * 7);
        int x = j / 2;
        gridView.setPadding(x, 0, 0, 0);// 居中
        
        return gridView;
    }
    
    // 上一个月
    private void setPrevViewItem()
    {
        iMonthViewCurrentMonth--;// 当前选择月--
        // 如果当前月为负数的话显示上一年
        if (iMonthViewCurrentMonth == -1)
        {
            iMonthViewCurrentMonth = 11;
            iMonthViewCurrentYear--;
        }
        calStartDate.set(Calendar.DAY_OF_MONTH, 1); // 设置日为当月1日
        calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth); // 设置月
        calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear); // 设置年
        
    }
    
    // 当月
    private void setToDayViewItem()
    {
        
        calSelected.setTimeInMillis(calToday.getTimeInMillis());
        calSelected.setFirstDayOfWeek(iFirstDayOfWeek);
        calStartDate.setTimeInMillis(calToday.getTimeInMillis());
        calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
        
    }
    
    // 下一个月
    private void setNextViewItem()
    {
        iMonthViewCurrentMonth++;
        if (iMonthViewCurrentMonth == 12)
        {
            iMonthViewCurrentMonth = 0;
            iMonthViewCurrentYear++;
        }
        calStartDate.set(Calendar.DAY_OF_MONTH, 1);
        calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
        calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
        
    }
    
    // 根据改变的日期更新日历
    // 填充日历控件用
    private void UpdateStartDateForMonth()
    {
        calStartDate.set(Calendar.DATE, 1); // 设置成当月第一天
        iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);// 得到当前日历显示的月
        iMonthViewCurrentYear = calStartDate.get(Calendar.YEAR);// 得到当前日历显示的年
        
        String s = calStartDate.get(Calendar.YEAR) + "-"
                + LeftPad_Tow_Zero(calStartDate.get(Calendar.MONTH) + 1);
        btnToday.setText(s);
        
        // 星期一是2 星期天是1 填充剩余天数
        int iDay = 0;
        int iFirstDayOfWeek = Calendar.MONDAY;
        int iStartDay = iFirstDayOfWeek;
        if (iStartDay == Calendar.MONDAY)
        {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
            if (iDay < 0)
                iDay = 6;
        }
        if (iStartDay == Calendar.SUNDAY)
        {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
            if (iDay < 0)
                iDay = 6;
        }
        calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);
        
    }
    
    private Calendar getCalendarStartDate()
    {
        calToday.setTimeInMillis(System.currentTimeMillis());
        calToday.setFirstDayOfWeek(iFirstDayOfWeek);
        
        if (calSelected.getTimeInMillis() == 0)
        {
            calStartDate.setTimeInMillis(System.currentTimeMillis());
            calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
        }
        else
        {
            calStartDate.setTimeInMillis(calSelected.getTimeInMillis());
            calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
        }
        
        return calStartDate;
    }
    
    public class TitleGridAdapter extends BaseAdapter
    {
        
        int[] titles = new int[] {R.string.Sun, R.string.Mon, R.string.Tue,
                R.string.Wed, R.string.Thu, R.string.Fri, R.string.Sat};
        
        private Activity activity;
        
        // construct
        public TitleGridAdapter(Activity a)
        {
            activity = a;
        }
        
        @Override
        public int getCount()
        {
            return titles.length;
        }
        
        @Override
        public Object getItem(int position)
        {
            return titles[position];
        }
        
        @Override
        public long getItemId(int position)
        {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            LinearLayout iv = new LinearLayout(activity);
            TextView txtDay = new TextView(activity);
            txtDay.setFocusable(false);
            txtDay.setBackgroundColor(Color.TRANSPARENT);
            iv.setOrientation(1);
            
            txtDay.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            lp.setMargins(1, 5, 1, 2);
            int i = (Integer)getItem(position);
            
            txtDay.setTextColor(Color.WHITE);
            Resources res = getResources();
            
            if (i == R.string.Sat)
            {
                // 周六
                txtDay.setBackgroundColor(res.getColor(R.color.title_text_6));
            }
            else if (i == R.string.Sun)
            {
                // 周日
                txtDay.setBackgroundColor(res.getColor(R.color.title_text_7));
            }
            else
            {
                
            }
            
            txtDay.setText((Integer)getItem(position));
            txtDay.setTextSize(18);
            //
            
            iv.addView(txtDay, lp);
            
            return iv;
        }
    }
    
    public String LeftPad_Tow_Zero(int str)
    {
        java.text.DecimalFormat format = new java.text.DecimalFormat("00");
        return format.format(str);
        
    }
    
    public void setAdpterSelectList(List<Date> list)
    {
        gAdapter.setSelectedList(list);
        gAdapter.notifyDataSetChanged();
        
        gAdapter1.setSelectedList(list);
        gAdapter1.notifyDataSetChanged();
        
        gAdapter3.setSelectedList(list);
        gAdapter3.notifyDataSetChanged();
    }
    
    /**设置提醒闹钟**/
    private void addAlarm(List<Plan> plans)
    {
        for (Plan plan : plans)
        {
            if(plan.getAlarm() == Plan.ALARM_YES)
            {
                LogUtil.d("提醒时间："+plan.getAlarmTime());
                Date date = DateUtil.strToDate(plan.getAlarmTime(), "yyyy-MM-dd HH:mm:ss");
                Intent intent = new Intent(PlanAddActivity2.this,AlarmActivity.class);
                intent.putExtra("title", plan.getTitle());
                PendingIntent pi = PendingIntent.getActivity(PlanAddActivity2.this, plan.getTitle().hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
                aManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pi);
            }
        }
    }
    /**设置定时器提前30分钟发短信通知好友提醒自己执行计划**/
    private void addAlarmForSms(List<Plan> plans)
    {
        if(!phoneList.isEmpty())
        {
            for (Plan plan : plans)
            {
                LogUtil.d("提醒时间："+plan.getAlarmTime());
                Date date = DateUtil.strToDate(plan.getAlarmTime(), "yyyy-MM-dd HH:mm:ss");
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                c.add(Calendar.MINUTE, -30);//提前30分钟发短信通知好友
                
                Intent intent = new Intent(PlanAddActivity2.this,AlarmForSmsService.class);
                intent.putExtra("title", plan.getTitle());
                intent.putExtra("phones", phoneList);
                //intent.setAction("com.fire8.dolphin.service.AlarmForSmsService");
                PendingIntent pi = PendingIntent.getService(PlanAddActivity2.this, plan.getTitle().hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
                aManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
            }
        }
        
    }
    //弹出窗口返回邀请的好友
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
        {
            return;
        }
        if (requestCode == ContactsActivity.class.hashCode())
        {
            if (resultCode == RESULT_OK)
            {
                 
                 ArrayList<HashMap<String, String>> sname = (ArrayList<HashMap<String, String>>)data.getExtras()
                        .getSerializable("selectNames");
                StringBuffer temp = new StringBuffer();
                if (sname != null && !sname.isEmpty())
                {
                    for (HashMap<String, String> hashMap : sname)
                    {
                        temp.append(hashMap.get("name")).append(",");
                        phoneList.add(hashMap.get("phone"));
                    }
                    tvFriends.setText(temp.toString());
                }
            }
        }
    }
    //提交计划
    private class SubmitPlanTask extends AsyncTask<Plan, Integer, String>
    {
        @Override
        protected String doInBackground(Plan... params)
        {
            if(!RequestUtils.getInstall().isConnect(PlanAddActivity2.this))
            {
                return "网络不可用";
            }
            StringBuffer sb = new StringBuffer();
            for (String str : phoneList)
            {
                sb.append(str).append(";");
            }
            //LogUtil.d("phoneList="+sb.toString());
            int len = params.length;
            for (int i = 0; i < len; i++)
            {
                Plan plan = params[i];
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("myPlan.title",plan.getTitle()));LogUtil.d("title"+plan.getTitle());
                param.add(new BasicNameValuePair("myPlan.alarmTime",plan.getAlarmTime()));
                param.add(new BasicNameValuePair("myPlan.alarm",String.valueOf(plan.getAlarm())));
                param.add(new BasicNameValuePair("myPlan.finish",String.valueOf(plan.getFinish())));
                param.add(new BasicNameValuePair("myPlan.isPublic",String.valueOf(plan.getIsPublic())));
                param.add(new BasicNameValuePair("myPlan.userId",String.valueOf(plan.getUserId())));
                param.add(new BasicNameValuePair("myPlan.phoneList",sb.toString()));
                String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"plan/addPlan.php", param);
                LogUtil.d("plan:"+json);
                try
                {
                    JSONObject data = new JSONObject(json);
                    String msgCode = data.getString("msgCode");
                    String desc = data.getString("desc");
                    if("1".equals(msgCode))
                    {
                        int id = data.getInt("msgBody");
                        plan.setsRemoteId(Long.valueOf(id));
                        pdDAO.update(plan);
                        LogUtil.d("修改计划ID="+id);
                    }
                }
                catch (Exception e)
                {
                    LogUtil.e("",e);
                }
                
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            //关闭提示
            progressDialog.dismiss();
            if(!StringUtil.isEmpty(result))
            {
                Toast.makeText(PlanAddActivity2.this, result, Toast.LENGTH_LONG).show();
            }
            PlanAddActivity2.this.finish();
        }
    }
    /**保存计划**/
    private class SavePlanListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            String strTitle = txtTitle.getText().toString();
            if(StringUtil.isEmpty(strTitle))
            {
                Toast.makeText(PlanAddActivity2.this, "请输入计划内容", Toast.LENGTH_LONG).show();
                return;
            }
            String hour = tvHour.getText().toString();
            String minute = tvMinute.getText().toString();
            if(!dlist.isEmpty())
            {
                for (Date date : dlist)
                {
                    Plan temp = new Plan();
                    temp.setDateTime(hour+":"+minute);
                    temp.setAlarmTime(DateUtil.getDayDate(date)+" "+temp.getDateTime()+":00");
                    temp.setTitle(strTitle);
                    temp.setsRemoteId(0l);
                    temp.setAlarm(checkbox.isChecked()==true?1:0);
                    temp.setFinish(Plan.FINISH_NO);
                    temp.setIsPublic(1);
                    
                    String userId = app.getUserId();
                    if(!StringUtil.isEmpty(userId))
                    {
                        temp.setUserId(Integer.valueOf(userId));
                    }
                    planList2.add(temp);
                }
                pdDAO.addList(planList2);
                addAlarm(planList2);//设置提醒闹钟
                //addAlarmForSms(planList2);
                //打开进度条窗口
                progressDialog = ProgressDialog.show(PlanAddActivity2.this, "请稍等...", "正在提交...", true);
                new SubmitPlanTask().execute(planList2.toArray(new Plan[]{}));
            }else
            {
                Toast.makeText(PlanAddActivity2.this, "您还没有选择计划日期", Toast.LENGTH_LONG).show();
            }    
        }
    }
}
